package com.fone.player.view;


import com.fone.player.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;


import android.widget.Button;

import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.ValueAnimator;

public class QuickPlayButton extends Button {

    public static final int IDLE_STATE_PROGRESS = 0;
    //public static final int ERROR_STATE_PROGRESS = -1;

    private Drawable background;

    private State mState;

    private int mColorIndicator;

    private float mStrokeWidth;
    
    private Matrix mCircleMatrix;
    
    private Bitmap mCircleBitmap;
    
    private RectF mRectF;
    private Paint mPaint;
    private Paint mBgPaint;
    
    private ValueAnimator mAnimation;
    

    private enum State {
        PROGRESS, IDLE, COMPLETE, ERROR;
    }

    private int mMaxProgress;
    private int mProgress;
    private int mInitProgress = 0;

    //private boolean mMorphingInProgress;
    
    private boolean mInStarting;

    public QuickPlayButton(Context context) {
        super(context);
        init(context, null);
    }

    public QuickPlayButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public QuickPlayButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attributeSet) {
       

        //initAttributes(context, attributeSet);
        
        mColorIndicator = 0xFFE67231;
        
        Resources res = context.getResources();  
		mCircleBitmap = BitmapFactory.decodeResource(res, R.drawable.home_quick_play_surface_2); 
		
		mCircleMatrix = new Matrix();

        mMaxProgress = 100;
        mState = State.IDLE;


        background = (Drawable) context.getResources().getDrawable(R.drawable.home_quick_play_surface);
        
        setBackgroundCompat(background);
    }

//    private void initAttributes(Context context, AttributeSet attributeSet) {
//        TypedArray attr = getTypedArray(context, attributeSet, R.styleable.CircularProgressButton);
//
//        if (attr == null) {
//            return;
//        }
//
//        try {
//            mIdleText = attr.getString(R.styleable.CircularProgressButton_textIdle);
//            mCompleteText = attr.getString(R.styleable.CircularProgressButton_textComplete);
//            mErrorText = attr.getString(R.styleable.CircularProgressButton_textError);
//
//            mIconComplete = attr.getResourceId(R.styleable.CircularProgressButton_iconComplete, 0);
//            mIconError = attr.getResourceId(R.styleable.CircularProgressButton_iconError, 0);
//            mCornerRadius = attr.getDimension(R.styleable.CircularProgressButton_cornerRadius, 0);

//            int blue = getColor(R.color.blue);
//            int red = getColor(R.color.red);
//            int green = getColor(R.color.green);
//            int white = getColor(R.color.white);
//            int grey = getColor(R.color.grey);

//            mColorIdle = attr.getColor(R.styleable.CircularProgressButton_colorIdle, blue);
//            mColorError = attr.getColor(R.styleable.CircularProgressButton_colorError, red);
//            mColorComplete = attr.getColor(R.styleable.CircularProgressButton_colorComplete, green);
//            mColorProgress = 0xE67231;
//            mColorIndicator = 0xFFE67231;
//            mColorIndicatorBackground = attr.getColor(R.styleable.CircularProgressButton_colorIndicatorBackground, grey);
            
//            Resources res = context.getResources();  
//    		mCircleBitmap = BitmapFactory.decodeResource(res, R.drawable.home_quick_play_surface_2); 
//    		
//    		mCircleMatrix = new Matrix();
//    		
//        } finally {
//            attr.recycle();
//        }
//    }
    
    @SuppressLint("NewApi")
	@Override
	protected void onVisibilityChanged(View changedView, int visibility) {
    	
		super.onVisibilityChanged(changedView, visibility);
		
//		if (visibility == VISIBLE) {
//			StartAnimation();
//		} else {
//			StopAnimation();
//		}
	}
    
    public void StartAnimation() {
    	
    	if (mInitProgress <= 0 ||mInitProgress >= 100){
    	
    		mAnimation = ValueAnimator.ofInt(1, 100);
    		mAnimation.setDuration(2000);
    	} else {
    		mAnimation = ValueAnimator.ofInt(1, mInitProgress);
    		mAnimation.setDuration(20*mInitProgress);
    		
    	}
    	
    		mAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
    		mAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    Integer value = (Integer) animation.getAnimatedValue();
                    progress(value);
                }
            });
//    		mAnimation.addListener(new AnimatorListener() {
//
//				@Override
//				public void onAnimationCancel(Animator arg0) {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onAnimationEnd(Animator arg0) {
//					// TODO Auto-generated method stub
//					setProgress(mInitProgress);
//				}
//
//				@Override
//				public void onAnimationRepeat(Animator arg0) {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onAnimationStart(Animator arg0) {
//					// TODO Auto-generated method stub
//					
//				}
//    			
//    		});
    		mAnimation.start();
        
    }
    
    private void StopAnimation() {
    	if (mAnimation != null)
    		mAnimation.cancel();
    }

    protected int getColor(int id) {
        return getResources().getColor(id);
    }

    protected TypedArray getTypedArray(Context context, AttributeSet attributeSet, int[] attr) {
        return context.obtainStyledAttributes(attributeSet, attr, 0, 0);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mProgress > 0 && mState == State.PROGRESS ) {
            doDraw(canvas);
        }
    }



    private void doDraw(Canvas canvas) {
    	mCircleMatrix.reset();
    	
        float sweepAngle = (360f / mMaxProgress) * mProgress;

        int offset = (getWidth() - getHeight()) / 2;

        Path path = new Path();
        path.addArc(getRect(), -90, sweepAngle);
        path.offset(offset, 0);
        canvas.drawPath(path, createPaint());

        
        float vw = getWidth();
		float vh = getHeight();
		float hvw = vw / 2;
		float hvh = vh / 2;
		float bw = (float) mCircleBitmap.getWidth();
		float bh = (float) mCircleBitmap.getHeight();

		// First scale the bitmap to fit into the view.
		// Use either scale factor for width and height,
		// whichever is the smallest.
		float s1x = vw / bw;
		float s1y = vh / bh;
		float s1 = (s1x < s1y) ? s1x : s1y;

		mCircleMatrix.postScale(s1, s1);

		// Translate the image up and left half the height
		// and width so rotation (below) is around the center.
		mCircleMatrix.postTranslate(-hvw, -hvh);

		mCircleMatrix.postRotate(sweepAngle);
		
		mCircleMatrix.postTranslate(hvw, hvh);
		
		canvas.drawBitmap(mCircleBitmap, mCircleMatrix, null);
		
		if (sweepAngle < 180) {

			path = new Path();
			path.addArc(getRect(), (-85 + sweepAngle), (355 - sweepAngle));
			path.offset(offset, 0);
			canvas.drawPath(path, createBGPaint());
		}

    }

    private RectF getRect() {
    	
    	
        if (mRectF == null) {
        	float gap = (getWidth())* 7f / 136f + 0.5f;
            mRectF = new RectF(gap, gap, getHeight() - gap, getHeight() - gap);
        }
        
        mStrokeWidth = (getWidth())* 4f/136f + 0.5f;
        return mRectF;
    }

    private Paint createPaint() {
        if (mPaint == null) {

            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(mStrokeWidth);
            mPaint.setColor(mColorIndicator);
        }

        return mPaint;
    }
    
    private Paint createBGPaint() {
        if (mBgPaint == null) {

        	mBgPaint = new Paint();
        	mBgPaint.setAntiAlias(true);
        	mBgPaint.setStyle(Paint.Style.STROKE);
        	mBgPaint.setStrokeWidth(mStrokeWidth);
        	mBgPaint.setColor(0xFF222222);
        }

        return mBgPaint;
    }

    private void toProgress() {

        setWidth(getWidth());

        mState = State.PROGRESS;
    }

    private void toComplete() {

        mState = State.COMPLETE;

    }



    private void toIdle() {

        mState = State.IDLE;
    }

    private void setIcon(int icon) {
        Drawable drawable = getResources().getDrawable(icon);
        if (drawable != null) {
            int padding = (getWidth() / 2) - (drawable.getIntrinsicWidth() / 2);
            //setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
            setPadding(padding, 0, 0, 0);
        }
    }

    protected void removeIcon() {
        //setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        //setPadding(0, 0, 0, 0);
    }

    /**
     * Set the View's background. Masks the API changes made in Jelly Bean.
     */
    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public void setBackgroundCompat(Drawable drawable) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
//            setBackground(drawable);
//        } else {
            setBackgroundDrawable(drawable);
//        }
    }

    private void progress(int progress) {
		mProgress = progress;

		if (mProgress >= mMaxProgress) {
			if (mState == State.PROGRESS) {
				toComplete();
			}
		} else if (mProgress > IDLE_STATE_PROGRESS) {
			if (mState == State.IDLE) {
				toProgress();
			} else if (mState == State.PROGRESS) {
				invalidate();
			}
		} else if (mProgress == IDLE_STATE_PROGRESS) {
			toIdle();
		}

    }
    
    public void setProgress(int progress) {
    	toProgress();
    	mProgress = progress;
    	invalidate();
    	
    }
    
    public void setInitProgress(int progress) {
    	
    	mInitProgress = progress;

    }

    public int getProgress() {
        return mProgress;
    }
}
